﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using WebSocketClient;

namespace WebSocketTest
{
    public partial class Form1 : Form
    {
        private static string url = "ws://127.0.0.1:5000/ws";
        private WSocketClient client = new WSocketClient(url);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            Control.CheckForIllegalCrossThreadCalls = false;
            txtServerIP.Text = url;
            client.MessageReceived = MessageReceived;
            this.Text = "客户端";
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (client.IsRunning)
                client.Dispose();
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                if (client.IsRunning)
                {
                    AddOrdinaryLog("已经连接服务器，不能重复执行");
                    return;
                }

                bool result = client.Start();
                AddOrdinaryLog("连接是否成功：" + result);
            }
            catch (Exception ex)
            {
                string err = string.Format("连接失败：{0}", ex.Message);
                Console.WriteLine(err);
                throw;
            }
        }

        /// <summary>
        /// 关闭服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (!client.IsRunning)
            {
                AddOrdinaryLog("服务器未连接");
                return;
            }
            // 记得释放资源否则会造成堆栈
            client.Dispose();
            AddOrdinaryLog("连接已关闭");
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            string inputMsg = txtInputMsg.Text;
            if (string.IsNullOrEmpty(inputMsg))
            {
                //MessageBox.Show("输入框不能为空");
                return;
            }

            //向指定房间发送消息
            Message mg = new Message();
            mg.Action = "send_to_room";
            mg.Msg = inputMsg;
            mg.Name = txtbox_name.Text;
            mg.SendClientId = "";
            var message = JsonConvert.SerializeObject(mg);
            client.SendMessage(message);

            AddOrdinaryLog(inputMsg);
            txtInputMsg.Text = string.Empty;
        }

        /// <summary>
        /// 服务端返回的消息
        /// </summary>
        private void MessageReceived(string msg)
        {
            AddOrdinaryLog(msg);
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="content"></param>
        private void AddOrdinaryLog(string content)
        {
            //读取当前ListBox列表长度
            int len = ListBox_OrdinaryLogList.Items.Count;
            //插入新的一行
            ListBox_OrdinaryLogList.Items.Insert(len, content);
            //列表长度大于30，那么就删除第1行的数据
            if (len > 30)
                ListBox_OrdinaryLogList.Items.RemoveAt(0);
            //插入新的数据后，将滚动条移动到最下面
            int visibleItems = ListBox_OrdinaryLogList.ClientSize.Height / ListBox_OrdinaryLogList.ItemHeight;
            ListBox_OrdinaryLogList.TopIndex = Math.Max(ListBox_OrdinaryLogList.Items.Count - visibleItems + 1, 0);
        }
        /// <summary>
        /// 加入房间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnroom_Click(object sender, EventArgs e)
        {
            //加入
            Message mg = new Message();
            mg.Action = "join";
            mg.Msg = txtbox_room.Text;
            mg.Name = txtbox_name.Text;
            mg.SendClientId = "";

            var message = JsonConvert.SerializeObject(mg);
            client.SendMessage(message);

        }
    }

}
